package com.tqz.rc.spring.cloud.ribbon.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import com.tqz.rc.api.Instance;
import com.tqz.rc.client.naming.NamingService;
import com.tqz.rc.common.exception.RcException;
import com.tqz.rc.spring.cloud.TqzRcProperties;
import com.tqz.rc.spring.cloud.TqzRcServiceManager;
import com.tqz.rc.spring.cloud.ribbon.TqzRcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>金丝雀版本权重负载均衡策略
 *
 * @author tianqingzhao
 * @since 2021/9/29 9:57
 */
public class TqzRcTheSameClusterPriorityWithVersionRule extends AbstractLoadBalancerRule {

    private static final Logger log = LoggerFactory.getLogger(TqzRcTheSameClusterPriorityWithVersionRule.class);

    private TqzRcServiceManager serviceManager;

    private TqzRcProperties properties;

    public TqzRcTheSameClusterPriorityWithVersionRule(TqzRcServiceManager serviceManager, TqzRcProperties properties) {
        this.serviceManager = serviceManager;
        this.properties = properties;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {
        try {
            String currentClusterName = properties.getClusterName();

            List<Instance> theSameClusterNameAndTheSameVersionInstList = getTheSameClusterAndTheSameVersionInstances(properties);

            // 声明被调用的实例
            Instance toBeChooseInstance;

            // 判断同集群同版本号的微服务实例是否为空
            if (theSameClusterNameAndTheSameVersionInstList.isEmpty()) {
                // 跨集群调用相同的版本
                toBeChooseInstance = crossClusterAndTheSameVersionInovke(properties);
            } else {
                toBeChooseInstance = TqzRcWeightedBalancer.chooseInstanceByRandomWeight(theSameClusterNameAndTheSameVersionInstList);
                log.info("同集群同版本调用--->当前微服务所在集群:{},被调用微服务所在集群:{},当前微服务的版本:{},Host:{},Port:{}",
                        currentClusterName, toBeChooseInstance.getClusterName(), toBeChooseInstance.getMetadata().get("current-version"),
                        toBeChooseInstance.getIp(), toBeChooseInstance.getPort());
            }

            return new TqzRcServer(toBeChooseInstance);

        } catch (RcException e) {
            log.error("同集群优先权重负载均衡算法选择异常:{}", e);
            return null;
        }
    }

    /**
     * 获取相同集群下,相同版本的 所有实例
     *
     * @param properties 注册中心的配置
     * @return
     * @throws RcException
     */
    private List<Instance> getTheSameClusterAndTheSameVersionInstances(TqzRcProperties properties) throws RcException {

        //当前的集群的名称
        String currentClusterName = properties.getClusterName();

        String currentVersion = properties.getMetadata().get("current-version");

        //获取所有实例的信息(包括不同集群的)
        List<Instance> allInstance = getAllInstances(properties);

        List<Instance> theSameClusterNameAndTheSameVersionInstList = new ArrayList<>();

        //过滤相同集群的
        for (Instance instance : allInstance) {
            if (StringUtils.endsWithIgnoreCase(instance.getClusterName(), currentClusterName) &&
                    StringUtils.endsWithIgnoreCase(instance.getMetadata().get("current-version"), currentVersion)) {

                theSameClusterNameAndTheSameVersionInstList.add(instance);
            }
        }

        return theSameClusterNameAndTheSameVersionInstList;
    }

    /**
     * 获取被调用服务的所有实例
     *
     * @param properties 注册中心的配置
     * @return
     * @throws RcException
     */
    private List<Instance> getAllInstances(TqzRcProperties properties) throws RcException {

        // 第1步:获取一个负载均衡对象
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) getLoadBalancer();

        // 第2步:获取当前调用的微服务的名称
        String invokedSerivceName = baseLoadBalancer.getName();

        // 第3步:获取nacos clinet的服务注册发现组件的api
        NamingService namingService = serviceManager.getNamingService(properties.getTqzRcProperties());

        // 第4步:获取所有的服务实例
        List<Instance> allInstance = namingService.selectInstances(invokedSerivceName);

        return allInstance;
    }

    /**
     * 跨集群环境下 相同版本的
     *
     * @param properties 注册中心的配置
     * @return
     * @throws RcException
     */
    private List<Instance> getCrossClusterAndTheSameVersionInstList(TqzRcProperties properties) throws RcException {
        // 版本号
        String currentVersion = properties.getMetadata().get("current-version");

        // 被调用的所有实例
        List<Instance> allInstance = getAllInstances(properties);

        List<Instance> crossClusterAndTheSameVersionInstList = new ArrayList<>();

        // 过滤相同版本
        for (Instance instance : allInstance) {
            if (StringUtils.endsWithIgnoreCase(instance.getMetadata().get("current-version"), currentVersion)) {

                crossClusterAndTheSameVersionInstList.add(instance);
            }
        }

        return crossClusterAndTheSameVersionInstList;
    }

    /**
     * 跨级群相同版本的调用
     *
     * @param properties
     * @return
     * @throws RcException
     */
    private Instance crossClusterAndTheSameVersionInovke(TqzRcProperties properties) throws RcException {

        // 获取所有集群下相同版本的实例信息
        List<Instance> crossClusterAndTheSameVersionInstList = getCrossClusterAndTheSameVersionInstList(properties);
        // 当前微服务的版本号
        String currentVersion = properties.getMetadata().get("current-version");
        // 当前微服务的集群名称
        String currentClusterName = properties.getClusterName();

        // 声明被调用的实例
        Instance toBeChooseInstance = null;

        // 没有对应相同版本的实例
        if (crossClusterAndTheSameVersionInstList.isEmpty()) {
            log.info("跨集群调用找不到对应合适的版本当前版本为:currentVersion:{}", currentVersion);
            throw new RuntimeException("找不到相同版本的微服务实例");
        } else {
            toBeChooseInstance = TqzRcWeightedBalancer.chooseInstanceByRandomWeight(crossClusterAndTheSameVersionInstList);

            log.info("跨集群同版本调用--->当前微服务所在集群:{},被调用微服务所在集群:{},当前微服务的版本:{},被调用微服务版本:{},Host:{},Port:{}",
                    currentClusterName, toBeChooseInstance.getClusterName(), properties.getMetadata().get("current-version"),
                    toBeChooseInstance.getMetadata().get("current-version"), toBeChooseInstance.getIp(), toBeChooseInstance.getPort());
        }

        return toBeChooseInstance;
    }
}
